package com.ice.app.system.config.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.ice.app.system.constants.SystemConstant;
import com.ice.app.system.entity.Config;
import com.ice.app.system.mapper.ConfigMapper;
import com.ice.app.system.utils.CacheUtils;
import com.iceframework.core.utils.KeyUtils;
import com.iceframework.core.utils.WebUtils;

/**
 * 
 * 业务逻辑层： 系统配置信息表
 * 
 * @author Mr.Palo
 * @email 442803840@qq.com
 * 
 */
@Service
public class ConfigService {

	@Autowired
	private ConfigMapper configMapper;

	// ----------------------------------------自动生成--------------------------------------------

	/**
	 * 菜单保存
	 * 
	 * @param config
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public boolean saveConfig(Config config) throws Exception {
		if (StringUtil.isNotEmpty(config.getId())) {
			// 修改操作
			Config old = this.getConfig(config.getId());
			config.setUpdateBy(WebUtils.getUserId());
			config.setUpdateDate(new Date());
			if (old != null) {
				return configMapper.updateByPrimaryKeySelective(config) > 0;
			}
			return false;
		} else {
			// 保存操作
			String key = KeyUtils.genKey("Organ");
			config.setId(key);
			config.setCreateBy("admin");
			config.setCreateDate(new Date());
			config.setUpdateBy("admin");
			config.setUpdateDate(new Date());
			return configMapper.insertSelective(config) > 0;

		}
	}

	/**
	 * 根据主键删除菜单
	 * 
	 * @param key
	 * @return
	 */
	@Transactional
	public boolean deleteConfig(String key) {
		return configMapper.deleteByPrimaryKey(key) > 0;
	}

	/**
	 * 根据多个主键删除菜单
	 * 
	 * @param keys
	 * @return
	 */
	@Transactional
	public boolean deleteConfigs(String keys) {
		if (!StringUtils.isEmpty(keys)) {
			String[] strs = keys.split(",");
			for (String key : strs) {
				this.deleteConfig(key);
			}
			return true;
		}
		return false;
	}

	/**
	 * 根据主键获取菜单实体
	 * 
	 * @param key
	 * @return
	 */
	public Config getConfig(String key) {
		return configMapper.selectByPrimaryKey(key);
	}

	/**
	 * 根据给定条件获取菜单实体集合
	 * 
	 * @param key
	 * @return
	 */
	public List<Config> getConfigs(Config config) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("config", config);
		return configMapper.selectByFilter(map);
	}

	/**
	 * 缓存配置
	 */
	public void cacheConfig() {
		List<Config> configs = getConfigs(new Config());
		for (Config config : configs) {
			CacheUtils.cacheObj(SystemConstant.CACHE_SYS_CONFIG  + ":" + config.getParamKey(), config.getParamValue());
		}
	}

	// ----------------------------------------自定义（Public）---------------------------------------------

}